from pydantic import BaseModel
from sqlalchemy import Column, Integer, String, TIMESTAMP, Column, DateTime, event, ForeignKey, Table
from datetime import datetime
from sqlalchemy.orm import relationship
from models.permission import Permission
from models.role_permission import role_permissions
from models.base import Base
from models.role_permission import role_permissions
from sqlalchemy.sql import func
from typing import Optional
metadata = Base.metadata

class Role(Base):
    def to_dict(self):
        return {c.name: getattr(self, c.name) for c in self.__table__.columns}

    __tablename__ = 'roles'
    __table_args__ = {'extend_existing': True}
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(255, 'utf8mb4_unicode_ci'), unique=True, comment='角色名')
    description = Column(String(255, 'utf8mb4_unicode_ci'), comment='角色描述')
    created_at = Column(DateTime(timezone=True), server_default=func.now(), comment='创建时间')
    updated_at = Column(DateTime(timezone=True), onupdate=func.now(), comment='更新时间')
    permissions = relationship('Permission', secondary=role_permissions, back_populates='roles')


# 为 MyModel 的每次更新添加事件监听
@event.listens_for(Role, 'before_update')
def receive_before_update(mapper, connection, target):
    target.updated_at = datetime.utcnow()

@event.listens_for(Role, 'before_insert')
def set_created_at(mapper, connection, target):
    if not target.created_at:
        target.created_at = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M")

class RoleSchema(BaseModel):
    id: int
    name: str
    description: str
    created_at: Optional[datetime] = None
    updated_at: Optional[datetime] = None
    deleted_at: Optional[datetime] = None

    class Config:
        orm_mode = True
        json_encoders = {
            datetime: lambda v: v.strftime('%Y-%m-%d %H:%M:%S') if v else None
        }
        from_attributes = True

